<template>
  <div>
    <panel title="JSON序列化">
      <div class="section">
        <Input v-model="json.input" @on-blur="formatJson" type="textarea" :rows="12"></Input>
        <ButtonGroup vertical>
          <Button type="primary" @click.native="encodeJson" icon="ios-arrow-forward">编码</Button>
          <Button type="success" @click.native="onCopyScript" :disabled="!json.output" icon="md-copy">复制结果</Button>
        </ButtonGroup>
        <Input ref="jsonOutput" v-model="json.output" type="textarea" :readonly="true" :rows="12"></Input>
      </div>
      </Row>
    </panel>
  </div>
</template>
<script>
export default {
  data() {
    return {
      json: {
        input: '',
        output: ''
      }
    };
  },
  methods: {
    formatJson() {
      try {
        let orginal = this.json.input;

        if(orginal.startsWith('=')){
          orginal = orginal.substr(1);
        }

        let json = JSON.stringify(JSON.parse(orginal), null, 2);

        this.json.input = json;
      } catch {

      }
    },
    encodeJson(){
      let bodyData = this.json.input;

      bodyData = bodyData.replace(/&/g, '%26')
               .replace(/\\/g, '%5C')
               .replace(/\+/g, '%2B')
               .replace(/>/g, '%3e')
               .replace(/</g, '%3c')
               .replace(/#/g, '%23')
               .replace(/~/g, '%40');

      console.log(bodyData);

      this.json.output = bodyData;
    },
    onCopyScript() {
      this.$copyText(this.$refs.jsonOutput.value).then(() => {
        this.$Message.success('代码已复制！');
      });
    }
  },
};
</script>
<style lang="less" scoped>
  .section {
    display: flex;
    flex-flow: nowrap;
    align-items: center;

    > .ivu-input-type-textarea{
      flex: 1;
    }

    > .ivu-btn-group-vertical{
      width: 100px;
      margin-left: 10px;
      margin-right: 10px;

      > .ivu-btn{
        border-radius: 7px;
        border-color: transparent;

        &:first-of-type{
          margin-bottom: 10px;
        }
      }
    }
  }
</style>
